import { ref, reactive, toRaw } from "vue";
/** dayjs */
import dayjs from "dayjs";

/** 跳转详情依赖 */
import { isString, isEmpty } from "@pureadmin/utils";
import { useMultiTagsStoreHook } from "@/store/modules/multiTags";
import {
  useRouter,
  useRoute,
  type LocationQueryRaw,
  type RouteParamsRaw
} from "vue-router";
/** 翻页器定义 */
import type { PaginationProps } from "@pureadmin/table";

/** api接口请求 */
import { getSummary, getOrderList } from "@/api/dashboard";

/** 图标 */
import ShoppingCartRemove from "@iconify-icons/mdi/shopping-cart-remove";
import ShoppingCartOutline from "@iconify-icons/mdi/shopping-cart-outline";
import AttachMoney from "@iconify-icons/mdi/attach-money";
import MoneyOff from "@iconify-icons/mdi/money-off";

/** 概览区域方法 */
export function useChart() {
  /** 时间段数据 */
  let timePeriodData = reactive({});

  /** 折线图配置数据 */
  const chartLineData = ref([
    {
      icon: ShoppingCartRemove,
      bgColor: "#fff5f4",
      color: "#e85f33",
      duration: 2200,
      name: "未发货",
      type: 1,
      value: 13,
      price: 0,
      data: []
    },
    {
      icon: ShoppingCartOutline,
      bgColor: "#effaff",
      color: "#41b6ff",
      duration: 1600,
      name: "已发货",
      type: 2,
      value: 807,
      price: 0,
      data: []
    },
    {
      icon: MoneyOff,
      bgColor: "#f6f4fe",
      color: "#7846e5",
      duration: 820,
      name: "未回款",
      type: 4,
      value: 820,
      price: 0,
      data: []
    },
    {
      icon: AttachMoney,
      bgColor: "#eff8f4",
      color: "#eacd76",
      duration: 150,
      name: "已回款",
      type: 3,
      value: 16499,
      price: 0,
      data: []
    }
  ]);

  /** 获取当日时间 */
  const today = dayjs().startOf("day").valueOf();
  /** 获取指定起始时间 */
  const pickDataList = reactive({
    yesterday: {
      starttime: dayjs().subtract(1, "day").startOf("day").valueOf()
    },
    thisweek: {
      starttime: dayjs().startOf("week").add(1, "day").valueOf()
    },
    thismounth: {
      starttime: dayjs().startOf("month").valueOf()
    },
    thisyear: {
      starttime: dayjs().startOf("year").valueOf()
    }
  });

  /** 日历组件数据 */
  const chooseTime = ref([pickDataList.thisyear.starttime, today]);
  /** 日期变化触发数据获取 */
  const getChartData = time => {
    let query = toRaw(time);
    if (query.length != 0) {
      getSummary(query).then(res => {
        timePeriodData = res.data;
        /** 未发货 */
        chartLineData.value[0].data = timePeriodData["notshipped"]["amplitude"];
        chartLineData.value[0].value = timePeriodData["notshipped"]["total"];
        chartLineData.value[0].price = timePeriodData["notshipped"]["amount"];
        /** 已发货 */
        chartLineData.value[1].data = timePeriodData["shipped"]["amplitude"];
        chartLineData.value[1].value = timePeriodData["shipped"]["total"];
        chartLineData.value[1].price = timePeriodData["shipped"]["amount"];
        /** 未回款 */
        chartLineData.value[2].data = timePeriodData["notpaid"]["amplitude"];
        chartLineData.value[2].value = timePeriodData["notpaid"]["total"];
        chartLineData.value[2].price = timePeriodData["notpaid"]["amount"];
        /** 已回款 */
        chartLineData.value[3].data = timePeriodData["paid"]["amplitude"];
        chartLineData.value[3].value = timePeriodData["paid"]["total"];
        chartLineData.value[3].price = timePeriodData["paid"]["amount"];
      });
    }
  };

  /** 自定义时间选择 */
  const changeCustom = () => {
    /** 模式4 自定义事件 */
    pickerMode.value = 4;
  };

  /** 日历快速选择时间段 */
  const date_shortcuts = [
    {
      text: "昨日",
      value: () => {
        pickerMode.value = 0;
        return [
          pickDataList.yesterday.starttime,
          pickDataList.yesterday.starttime
        ];
      }
    },
    {
      text: "本周",
      value: () => {
        pickerMode.value = 1;
        return [pickDataList.thisweek.starttime, today];
      }
    },
    {
      text: "本月",
      value: () => {
        pickerMode.value = 2;
        return [pickDataList.thismounth.starttime, today];
      }
    },
    {
      text: "本年",
      value: () => {
        pickerMode.value = 3;
        return [pickDataList.thisyear.starttime, today];
      }
    }
  ];

  /** 日历禁用时间 */
  const disabledDate = (time: Date) => {
    return time.getTime() > Date.now();
  };

  /** 日期按钮数据 */
  let pickerMode = ref(3); // 默认状态 本年

  /** 按钮改变事件 */
  const changePickerMode = val => {
    chooseTime.value = val.option.date;
  };

  /** 日期按钮配置 */
  const optionsBasis: Array<any> = [
    {
      label: "昨日", // 0
      date: [pickDataList.yesterday.starttime, pickDataList.yesterday.starttime]
    },
    {
      label: "本周", //1
      date: [pickDataList.thisweek.starttime, today]
    },
    {
      label: "本月", //2
      date: [pickDataList.thismounth.starttime, today]
    },
    {
      label: "本年", //3
      date: [pickDataList.thisyear.starttime, today]
    },
    {
      label: "自定义", //4,
      date: []
    }
  ];

  // 页面首次加载
  return {
    timePeriodData,
    chartLineData,
    pickerMode,
    today,
    pickDataList,
    chooseTime,
    optionsBasis,
    date_shortcuts,
    getChartData,
    changeCustom,
    disabledDate,
    changePickerMode
  };
}

/** 详细数据表格 */
export function useTable() {
  // ⚙️状态初始化
  const formRef = ref();
  /** 是否处于 Loding 状态 */
  const loading = ref(true);
  /** 表格数据 */
  const dataList = ref([]);
  /** 活动卡片 */
  const activeCardIndex = ref(0);
  /** 订单类型 */
  const orderType = ref(1);
  /** 翻页器定义 */
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 15,
    currentPage: 1,
    background: true
  });

  /**
   * @description: 订单详情搜索方法
   * @param {Array} timePeriod 时间段列表
   */
  async function onSearch(timePeriod: Array<number>) {
    loading.value = true;
    let searchTime = toRaw(timePeriod);
    getOrderList({
      typeid: orderType.value,
      starttime: searchTime[0] / 1000,
      endtime: searchTime[1] / 1000,
      page: pagination.currentPage,
      size: pagination.pageSize
    }).then(res => {
      dataList.value = res.data.orderlist;
      pagination.total = res.data.total;
      loading.value = false;
      return res;
    });
  }

  /** 翻页器-改变页大小 */
  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch(useChart().chooseTime.value);
  }
  /** 翻页器-改变页数 */
  function handleCurrentChange(val) {
    pagination.currentPage = val;
    onSearch(useChart().chooseTime.value);
  }
  /** 表格字段信息 */
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "订单编号",
      prop: "orderno",
      sortable: true,
      width: 90
    },
    {
      label: "时间",
      prop: "orderdate",
      sortable: true,
      minWidth: 130
    },
    {
      label: "单位名称",
      prop: "purchasingunit",
      minWidth: 130
    },
    {
      label: "收货人",
      prop: "contactsname",
      minWidth: 130
    },
    {
      label: "订单金额",
      prop: "price",
      sortable: true,
      minWidth: 130
    },
    {
      label: "订单状态",
      prop: "status",
      minWidth: 90,
      cellRenderer: ({ row, props }) => {
        const { color, textColor } = getOrderTagProps(row.status);
        return (
          <el-tag
            size={props.size}
            color={color}
            style={{ color: textColor, border: `1px solid ${color}` }}
          >
            {row.status}
          </el-tag>
        );
      }
    },
    {
      label: "快递状态",
      prop: "logisticsstatus",
      minWidth: 90,
      cellRenderer: ({ row, props }) => {
        const { color, textColor } = getDeliveryTagProps(row.logisticsstatus);
        return (
          <el-tag
            size={props.size}
            color={color}
            style={{ color: textColor, border: `1px solid ${color}` }}
          >
            {row.logisticsstatus || "未发货"}
          </el-tag>
        );
      }
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];

  type OrderStatus = "未发货" | "未开票" | "未回款" | "已回款";
  /** 获取订单状态标签样式 */
  const getOrderTagProps = (status: OrderStatus) => {
    switch (status) {
      case "未发货":
        return {
          color: "#fff5f4",
          textColor: "#e85f33"
        };
      case "未开票":
        return {
          color: "#e8f4ff",
          textColor: "#1e90ff"
        };
      case "未回款":
        return {
          color: "#d4f4e4",
          textColor: "#4caf50"
        };
      case "已回款":
        return {
          // color: "#fef6f6",
          color: "#f0f9eb",
          // textColor: "#ff6f6f"
          textColor: "#00b8a9"
        };
      default:
        return {
          color: "#f0f0f0",
          textColor: "#000"
        };
    }
  };

  type DeliveryStatus = "进行中" | "已完成" | "";
  /** 获取订单状态标签样式 */
  const getDeliveryTagProps = (status: DeliveryStatus) => {
    switch (status) {
      case "":
        return {
          color: "#fff5f4",
          textColor: "#e85f33"
        };
      case "进行中":
        return {
          color: "#ecf5ff",
          textColor: "#619eff"
        };
      case "已完成":
        return {
          color: "#f0f9eb",
          textColor: "#67c23a"
        };
      default:
        return {
          color: "#f0f0f0",
          textColor: "#000"
        };
    }
  };

  /** 卡片点击事件 */
  const onCardClick = (index, timePeriod: Array<number>, type: number) => {
    activeCardIndex.value = index;
    orderType.value = type;
    onSearch(timePeriod);
  };

  return {
    formRef,
    loading,
    dataList,
    pagination,
    columns,
    activeCardIndex,
    onSearch,
    onCardClick,
    handleSizeChange,
    handleCurrentChange
  };
}

/** 跳转详情页方法 */
export function useDetail() {
  const route = useRoute();
  const router = useRouter();
  const getParameter = isEmpty(route.params) ? route.query : route.params;

  function toDetail(
    parameter: LocationQueryRaw | RouteParamsRaw,
    model: "query" | "params"
  ) {
    Object.keys(parameter).forEach(param => {
      if (!isString(parameter[param])) {
        parameter[param] = parameter[param].toString();
      }
    });
    if (model === "query") {
      // 保存信息到标签页
      useMultiTagsStoreHook().handleTags("push", {
        path: `/tabs/query-detail`,
        name: "TabQueryDetail",
        query: parameter,
        meta: {
          title: {
            zh: `No.${parameter.id} - 详情信息`,
            en: `No.${parameter.id} - DetailInfo`
          },
          // 如果使用的是非国际化精简版title可以像下面这么写
          // title: `No.${index} - 详情信息`,
          // 最大打开标签数
          dynamicLevel: 3
        }
      });
      // 路由跳转
      router.push({ name: "TabQueryDetail", query: parameter });
    } else if (model === "params") {
      useMultiTagsStoreHook().handleTags("push", {
        path: `/dashboard/order/:id`,
        name: "OrderDetail",
        params: parameter,
        meta: {
          title: `订单 ${parameter.id}`
          // title: {
          //   zh: `No.${parameter.id} - 详情信息`,
          //   en: `No.${parameter.id} - DetailInfo`
          // }
          // 如果使用的是非国际化精简版title可以像下面这么写
          // title: `No.${index} - 详情信息`,
        }
      });
      router.push({ name: "OrderDetail", params: parameter });
    }
  }

  // 用于页面刷新，重新获取浏览器地址栏参数并保存到标签页
  const initToDetail = (model: "query" | "params") => {
    if (getParameter) toDetail(getParameter, model);
  };

  return { toDetail, initToDetail, getParameter, router };
}
